import { db } from "@/db/db";
import { router } from "@/router/router";
import { MenuModel } from "@/share/models";
import { MenuSignal } from "@/share/signals/index";
import { Like } from "typeorm";

export class MenuService {
  // 列表
  @router(MenuSignal.List)
  static async lists(c: Context<DTO.Menu.ListParams>) {
    const params = c.params;
    const repository = db.getRepository(MenuModel);

    // 根据关键词查询符合匹配条件的总数
    const count = await repository.countBy([{ name: Like(`%${params.name}%`) }]);

    console.log(count);

    // 根据总数和当前页数调整pageNum，以避免无效的分页请求
    if ((params.pageNum - 1) * params.pageSize > count) {
      params.pageNum = Math.ceil(count / params.pageSize);
    }

    // 查询符合匹配条件的列表及总数量，用于分页显示
    const [list, total] = await repository.findAndCount({
      skip: (params.pageNum - 1) * params.pageSize,
      take: params.pageSize,
      where: [{ name: Like(`%${params.name}%`) }],
      order: { createTime: "DESC" }
    });

    // 返回查询结果及分页信息
    return c.success({ list, total, pageNum: params.pageNum, pageSize: params.pageSize });
  }
  // 创建
  @router(MenuSignal.Create)
  static async create(c: Context<DTO.Menu.CreateParams>) {
    const params = c.params;
    const repository = db.getRepository(MenuModel);
    // 如果不存在则创建，默认密码123456
    const user = new MenuModel();
    user.name = params.name;
    user.parentId = params.parentId;
    user.url = params.url;
    user.icon = params.icon;
    user.sort = params.sort;
    user.remark = params.remark;
    user.createBy = c.user.username;
    user.updateBy = c.user.username;
    const saved = await repository.save(user);
    return c.success(saved);
  }

  // 批量删除
  @router(MenuSignal.Deletes)
  static async deletes(c: Context<DTO.Menu.DeletesParams>) {
    const params = c.params;
    const repository = db.getRepository(MenuModel);
    await repository.delete(params.ids);
    return c.success();
  }

  // 修改
  @router(MenuSignal.Update)
  static async update(c: Context<DTO.Menu.UpdateParams>) {
    const params = c.params;
    const repository = db.getRepository(MenuModel);
    await repository.update(params.id, {
      ...params
    });
    // 返回操作成功的响应
    return c.success();
  }
}
